<script setup>
import { ref } from 'vue'
import {userInfoUpdatePwdService} from '@/api/user'
import {ElMessage} from "element-plus"
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores'

const formModel = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 表单元素规则校验
const rules = {
  old_pwd: [
    {required: true, message: '请输入原密码', trigger: 'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '原密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '新密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === formModel.value.old_pwd) {
          callback(new Error("原密码和新密码不能一样！"))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  re_pwd: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.new_pwd) {
          callback(new Error("两次密码不一致"))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const form = ref()
const router = useRouter()
const userStore = useUserStore()
// 修改用户密码
const updatePwd = async () => {
  await form.value.validate()
  await userInfoUpdatePwdService(formModel.value)
  ElMessage.success('修改密码成功')

  // 清空用户信息 跳转登录页
  userStore.removeToken()
  userStore.removeUser()
  await router.push('/login')
}

// 重置表单
const reset = () => {
  formModel.value = {}
}
</script>

<template>
  <PageContainer title="重置密码">
    <el-form ref="form" :model="formModel" :rules="rules" label-width="100px" size="large"
             style="padding-right: 50%">
      <el-form-item prop="old_pwd" label="原密码">
        <el-input type="password" v-model="formModel.old_pwd"></el-input>
      </el-form-item>
      <el-form-item prop="new_pwd" label="新密码">
        <el-input type="password" v-model="formModel.new_pwd"></el-input>
      </el-form-item>
      <el-form-item prop="re_pwd" label="确认新密码">
        <el-input type="password" v-model="formModel.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>

<style scoped>

</style>
